package com.zy.is.service.impl;

import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import com.zy.is.common.exception.VerifyException;
import com.zy.is.common.utils.SignUtil;
import com.zy.is.domain.SysUser;
import com.zy.is.mapper.SysUserMapper;
import com.zy.is.service.SysUserService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.security.SignatureException;

/**
 * @ClassName: SysUserServiceImpl
 * @Description: 系统用户服务实现
 * @Author: Yanzy
 * @Data: 2021/4/2 13:46
 * @Source: 1.0
 */
@Slf4j
@Service
public class SysUserServiceImpl implements SysUserService {

    @Resource
    private SysUserMapper sysUserMapper;

    @Override
    public SysUser findSysUserById(String id) {
        return sysUserMapper.selectById(id);
    }

    @Override
    public SysUser findSysUserByName(String loginName) {
        return sysUserMapper.findSysUserByName(loginName);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public int insertSysUser(SysUser sysUser) throws Exception {

        // 验证用户名唯一
        SysUser sysUserByName = findSysUserByName(sysUser.getLoginName());
        if (null != sysUserByName) {
            log.debug("登录名重复: {}", sysUser.getLoginName());
            throw new VerifyException("登录名重复");
        }
        // 密码加密
        String sign = null;
        try {
            sign = SignUtil.shiroMd5(sysUser.getLoginPwd(), sysUser.getLoginName());
        } catch (Exception e) {
            log.debug("用户保存密码加密异常: {}", e.getMessage());
            throw new SignatureException(StringUtils.format("加密异常: {}", e.getMessage()));
        }
        sysUser.setLoginPwd(sign);
        return sysUserMapper.insert(sysUser);
    }
}
